package com.xinfu.newproject.ui.complaint_feedback;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alley.van.VanGogh;
import com.alley.van.helper.VanCropType;
import com.alley.van.helper.VanMediaFilter;
import com.alley.van.helper.VanMediaType;
import com.alley.van.model.VanConfig;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.xinfu.newproject.R;
import com.xinfu.newproject.activity.ComplaintFeedbackActivity;
import com.xinfu.newproject.activity.ResidentCertificationActivity;
import com.xinfu.newproject.adapter.matter_repair_adapter.RepairImageAdapter;
import com.xinfu.newproject.base.BaseActivity;
import com.xinfu.newproject.bean.certifition.ResidentBean;
import com.xinfu.newproject.bean.certifition.ResidentCertificationBean;
import com.xinfu.newproject.bean.complaint.bean.ComplaintDetailBean;
import com.xinfu.newproject.bean.complaint.bean.ComplaintEvaluateBean;
import com.xinfu.newproject.bean.complaint.bean.ComplaintRecordBean;
import com.xinfu.newproject.bean.complaint.bean.SubmitComplaintBean;
import com.xinfu.newproject.bean.login.LoginBean;
import com.xinfu.newproject.bean.up_image.UpImageBean;
import com.xinfu.newproject.contants.Contants;
import com.xinfu.newproject.presenter.ComplaintPresenter;
import com.xinfu.newproject.presenter.UpImagePresenter;
import com.xinfu.newproject.test.GifSizeFilter;
import com.xinfu.newproject.test.GlideImageLoader;
import com.xinfu.newproject.test.VanToast;
import com.xinfu.newproject.util.BToast;
import com.xinfu.newproject.util.GetImagePathUtil;
import com.xinfu.newproject.util.SPUtils;
import com.xinfu.newproject.util.WHelperUtil;
import com.xinfu.newproject.view.IView;
import com.xinfu.newproject.widget.CustomClickListener;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

import static com.xinfu.newproject.contants.Constant.LOGIN;
import static com.xinfu.newproject.contants.Contants.REQUEST_CODE_AVATAR;
import static com.xinfu.newproject.contants.Contants.REQUEST_CODE_IMAGE;

public class ComplaintsFragment extends BaseActivity implements IView.IComplaintView, RepairImageAdapter.RemoveOnClickListener, IView.IUpImageView {

    @BindView(R.id.head_right_text)
    TextView rightTv;

    @BindView(R.id.layout_choose_person_info_time)
    TextView chooseTimeTv;

    @BindView(R.id.layout_choose_person_info_id)
    TextView chooseIdTv;

    @BindView(R.id.layout_next_step_tv)
    TextView submitTv;

    @BindView(R.id.layout_choose_person_info_name_et)
    EditText nameTv;

    @BindView(R.id.layout_choose_person_info_phone_et)
    EditText phoneTv;

    @BindView(R.id.fragment_complaint_content_et)
    EditText contentEt;

    @BindView(R.id.fragment_complaint_community_tv)
    TextView communityTv;

    @BindView(R.id.fragment_complaint_complaint_tv)
    TextView complaintTv;

    @BindView(R.id.fragment_complaint_advice_tv)
    TextView adviceTv;

    @BindView(R.id.fragment_complaint_complaint_view)
    View complaintView;

    @BindView(R.id.fragment_complaint_advice_view)
    View adviceView;

    @BindView(R.id.layout_up_image_rv)
    RecyclerView imageRecyclerView;

    private RepairImageAdapter repairImageAdapter;
    private int isImage = 0;
    private ArrayList<String> imageList = new ArrayList<>();
    private String type = "1";
    private static final int REQUEST_CODE_CHOOSE = 23;
    private static final int REQUEST_CODE_CAMERA = 32;
    private ComplaintPresenter complaintPresenter = new ComplaintPresenter(this);
    private UpImagePresenter upImagePresenter = new UpImagePresenter(this);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_complaint);
        ButterKnife.bind(this);
        registerBack();
        initViewBind();
        initLisener();
    }

    private void initLisener() {
        LoginBean.ResultBean resultBean;
        String responseIntent = (String) SPUtils.get(this, LOGIN, "0");
        if (!responseIntent.equals("0")) {
            resultBean = new Gson().fromJson(responseIntent, LoginBean.ResultBean.class);
            token = resultBean.getToken();
            userId = resultBean.getUserInfo().getId();
            userName = resultBean.getUserInfo().getUsername();
            nameTv.setText(resultBean.getUserInfo().getUsername());
            phoneTv.setText(resultBean.getUserInfo().getPhone());
        } else {
            BToast.showText(this, "未登录");
        }
        contentEt.setFilters(new InputFilter[]{inputFilter});

        submitTv.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (isLogin()) {
                    showLoding();
                    if (imageList.size() > 0) {
                        if (isImage == 1) {
                            upImagePresenter.upImage();
                        } else {
                            BToast.showText(ComplaintsFragment.this, "请上传图片");
                            hideLoding();
                        }
                    } else {
                        BToast.showText(ComplaintsFragment.this, "请上传图片");
                        hideLoding();
                    }

                }
            }

            @Override
            protected void onFastClick() {

            }
        });
    }

    InputFilter inputFilter = new InputFilter() {
        Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {
                BToast.showText(ComplaintsFragment.this, "暂不支持输入表情");
                return "";
            }
            return null;
        }
    };

    private void initViewBind() {
        chooseIdTv.setVisibility(View.GONE);
        chooseTimeTv.setVisibility(View.GONE);
        setActivityTitle("投诉建议");
        rightTv.setText("记录");
        submitTv.setText("我要投诉");
        rightTv.setVisibility(View.VISIBLE);
        imageRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        repairImageAdapter = new RepairImageAdapter(this);
        imageRecyclerView.setAdapter(repairImageAdapter);
        imageList.add(0, "0");
        repairImageAdapter.setNewData(imageList);
        repairImageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (imageList.get(position).equals("0")) {
                    isCode = REQUEST_CODE_AVATAR;
                    onClickCamera();
                } else {
                    isCode = REQUEST_CODE_IMAGE;
                    imagePosition = position;
                    onClickCamera();
                }
            }
        });
    }

    int isCode;

    @Override
    public void permissionGrant(boolean isGranted, int requestCode) {
        super.permissionGrant(isGranted, requestCode);
        if (!isGranted) {
            return;
        }
        switch (requestCode) {
            case 0x0001://拍照
                VanGogh.from(ComplaintsFragment.this)
                        .choose(VanMediaType.ofAll())//拍照时，无效
                        .cameraVisible(true, getPackageName())//拍照时，第一个参数无效
                        .withResultSize(1024, 1024)
                        .cropEnable(false, VanCropType.CROP_TYPE_RECTANGLE)//第一个参数为FALSE时，第二个参数无效
                        .theme(R.style.VanTheme_ActivityAnimation)
                        .thumbnailScale(0.85f)
                        .toast(new VanToast())
                        .imageLoader(new GlideImageLoader())
                        .forCamera(REQUEST_CODE_CAMERA);
                break;

            case 0x0002://从相册选择
                int maxCount;
                if (isCode == REQUEST_CODE_AVATAR) {
                    maxCount = 5 - imageList.size();
                } else {
                    maxCount = 4;
                }
                VanGogh.from(ComplaintsFragment.this)
                        .choose(VanMediaType.ofAll())
                        .countable(true)//若开启裁剪，则无效
                        .maxCount(maxCount)
                        .rowCount(3)
                        .cameraVisible(true, getPackageName())//设置在第一个参数为FALSE时，第二个参数无效
                        .withResultSize(1024, 1024)
                        .cropEnable(false, VanCropType.CROP_TYPE_RECTANGLE)//第一个参数为TRUE时，则可选中数量被设为1，此时maxSelectable(9)无效；第一个参数为FALSE时，第二个参数无效
                        .theme(R.style.VanTheme_Dracula)
                        .addFilter(new GifSizeFilter(320, 320, 5 * VanMediaFilter.K * VanMediaFilter.K))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                        .thumbnailScale(0.85f)
                        .toast(new VanToast())
                        .imageLoader(new GlideImageLoader())
                        .forResult(REQUEST_CODE_CHOOSE);
                break;

            default:
                break;
        }
    }


    @OnClick({R.id.fragment_complaint_community_tv, R.id.fragment_complaint_complaint_tv, R.id.fragment_complaint_advice_tv, R.id.head_right_text})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fragment_complaint_community_tv:
                Bundle bundle = new Bundle();
                bundle.putInt("type", Contants.CHOOSECOMMUNITYCERTIFITION);
                startActivityForResult(new Intent(this, ResidentCertificationActivity.class).putExtras(bundle), Contants.CHOOSECOMMUNITYCERTIFITION);
                break;
            case R.id.fragment_complaint_complaint_tv:
                complaintView.setVisibility(View.VISIBLE);
                adviceView.setVisibility(View.INVISIBLE);
                complaintTv.setTextColor(getResources().getColor(R.color.yellow_ff));
                adviceTv.setTextColor(getResources().getColor(R.color.gray_a5));
                type = "1";
                if (submitTv.getText().equals("我要建议")) {
                    contentEt.getText().clear();
                    contentEt.setHint("请详细描述投诉内容");
                    imageList.clear();
                    imageList.add("0");
                    repairImageAdapter.setNewData(imageList);
                    isImage = 0;
                    projectId = null;
                }
                submitTv.setText("我要投诉");
                communityTv.setText("请选择小区");

                break;
            case R.id.fragment_complaint_advice_tv:
                complaintView.setVisibility(View.INVISIBLE);
                adviceView.setVisibility(View.VISIBLE);
                complaintTv.setTextColor(getResources().getColor(R.color.gray_a5));
                adviceTv.setTextColor(getResources().getColor(R.color.yellow_ff));
                type = "0";
                if (submitTv.getText().equals("我要投诉")) {
                    contentEt.getText().clear();
                    contentEt.setHint("请详细描述建议内容");
                    imageList.clear();
                    imageList.add("0");
                    repairImageAdapter.setNewData(imageList);
                    isImage = 0;
                    projectId = null;
                }
                submitTv.setText("我要建议");
                communityTv.setText("请选择小区");
                break;
            case R.id.head_right_text:
                startIntentActivity(ComplaintFeedbackActivity.class, null);
                break;
        }
    }

    ResidentBean residentBean;
    Integer imagePosition;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            final ArrayList<String> pathList = new ArrayList<>();
            switch (requestCode) {
                case REQUEST_CODE_CHOOSE:
                    if (VanGogh.obtainResult(data) != null) {
                        if (VanGogh.obtainResult(data).size() > 0) {
                            for (int i = 0; i < VanGogh.obtainResult(data).size(); i++) {
                                pathList.add(GetImagePathUtil.getRealFilePath(this, VanGogh.obtainResult(data).get(i)));
                            }
                        }
                    }
                    if (isCode == REQUEST_CODE_AVATAR) {
                        if ((imageList.size() - 1) < pathList.size()) {
                            if (imageList.size() == 1) {
                                imageList.clear();
                            } else {
                                imageList.remove(imageList.size() - 1);
                            }
                            for (int i = 0; i < pathList.size(); i++) {
                                imageList.add(i, pathList.get(i));
                            }
                        } else if ((5 - imageList.size()) >= pathList.size()) {
                            if (imageList.size() == 1) {
                                imageList.clear();
                            } else {
                                imageList.remove(imageList.size() - 1);
                            }
                            for (int i = 0; i < pathList.size(); i++) {
                                imageList.add(pathList.get(i));
                            }
                        }
                        isImage = 1;
                    } else {
                        if (pathList != null) {
                            if (pathList.size() > 0) {
                                if (pathList.size() == 1 && !pathList.get(0).equals("")) {
                                    if (imagePosition != null) {
                                        imageList.set(imagePosition, pathList.get(0));
                                    }
                                } else {
                                    if (!pathList.get(0).equals("")) {
                                        imageList.clear();
                                        for (int i = 0; i < pathList.size(); i++) {
                                            imageList.add(i, pathList.get(i));
                                        }
                                    }
                                }
                            }
                        }
                        imagePosition = null;
                        isImage = 1;
                    }
                    break;
                case REQUEST_CODE_CAMERA:

                    Uri contentUri = VanGogh.obtainCamera();
                    if (contentUri == null) {
                        return;
                    }

                    if (!VanConfig.getInstance().cropEnable) {

                        pathList.add(GetImagePathUtil.getRealFilePath(this, contentUri));
                    }
                    if (isCode == REQUEST_CODE_AVATAR) {
                        if ((imageList.size() - 1) < pathList.size()) {
                            if (imageList.size() == 1) {
                                imageList.clear();
                            } else {
                                imageList.remove(imageList.size() - 1);
                            }
                            for (int i = 0; i < pathList.size(); i++) {
                                imageList.add(i, pathList.get(i));
                            }
                        } else if ((5 - imageList.size()) >= pathList.size()) {
                            if (imageList.size() == 1) {
                                imageList.clear();
                            } else {
                                imageList.remove(imageList.size() - 1);
                            }
                            for (int i = 0; i < pathList.size(); i++) {
                                imageList.add(pathList.get(i));
                            }
                        }
                        isImage = 1;
                    } else {
                        if (pathList != null) {
                            if (pathList.size() > 0) {
                                if (pathList.size() == 1 && !pathList.get(0).equals("")) {
                                    if (imagePosition != null) {
                                        imageList.set(imagePosition, pathList.get(0));
                                    }
                                } else {
                                    if (!pathList.get(0).equals("")) {
                                        imageList.clear();
                                        for (int i = 0; i < pathList.size(); i++) {
                                            imageList.add(i, pathList.get(i));
                                        }
                                    }
                                }
                            }
                        }
                        imagePosition = null;
                        isImage = 1;
                    }
                    break;
                case Contants.CHOOSECOMMUNITYCERTIFITION:
                    if (data.getExtras().getString("community") != null) {
                        residentBean = new Gson().fromJson(data.getExtras().getString("community"), ResidentBean.class);
                        ResidentCertificationBean.ResultBean.RoomCheckUserListBean video = (ResidentCertificationBean.ResultBean.RoomCheckUserListBean) residentBean.t;
//                        roomId = video.getRoomId();
                        communityTv.setText(data.getExtras().getString("title") + "\n" + video.getAddress());
                    }
                    break;
            }
            for (int i = 0; i < imageList.size(); i++) {
                if (imageList.get(i).equals("0")) {
                    imageList.remove(i);
                }
            }
            if (imageList.size() < 4) {
                imageList.add("0");
            }
            repairImageAdapter.setNewData(imageList);
        }
    }

    /**
     * 判断是否可以请求数据
     */
    String token, userId, userName, projectId;
    int tenandId;

    private boolean isLogin() {

        LoginBean.ResultBean resultBean;
        String responseIntent = (String) SPUtils.get(this, LOGIN, "0");
        if (!responseIntent.equals("0")) {
            resultBean = new Gson().fromJson(responseIntent, LoginBean.ResultBean.class);
            token = resultBean.getToken();
            userId = resultBean.getUserInfo().getId();
            userName = resultBean.getUserInfo().getUsername();
        } else {
            BToast.showText(this, "未登录");
            return false;
        }

        if (TextUtils.isEmpty(contentEt.getText().toString())) {
            BToast.showText(this, "请填写完整信息");
            return false;
        }
        if (contentEt.getText().toString().trim().equals("")) {
            BToast.showText(this, "请填写完整信息");
            return false;
        }
        if (TextUtils.isEmpty(nameTv.getText())) {
            BToast.showText(this, "请填写完整信息");
            return false;
        }
        if (TextUtils.isEmpty(phoneTv.getText())) {
            BToast.showText(this, "请填写完整信息");
            return false;
        } else {
            if (!WHelperUtil.isMobileRight(this, phoneTv.getText().toString())) {
                BToast.showText(this, "请填写正确的手机号");
                return false;
            }
        }


        if (residentBean == null) {
            BToast.showText(this, "请填写完整信息");
            return false;
        }
        if (responseIntent == null) {
            BToast.showText(this, "请填写完整信息");
            return false;
        }

        ResidentCertificationBean.ResultBean.RoomCheckUserListBean video = (ResidentCertificationBean.ResultBean.RoomCheckUserListBean) residentBean.t;
        projectId = video.getProjectId();
        tenandId = video.getTenantId();
        if (projectId == null) {
            BToast.showText(this, "请填写完整信息");
            return false;
        }

//        Log.i("testProjectId", projectId);
        return true;
    }


    @Override
    public String header() {
        return token;
    }

    @Override
    public List<String> imageList() {
        return imageList;
    }

    @Override
    public Context context() {
        return this;
    }

    @Override
    public String userId() {
        return userId;
    }

    @Override
    public String type() {
        return type;
    }

    @Override
    public String name() {
        return nameTv.getText().toString().trim();
    }

    @Override
    public String telephone() {
        return phoneTv.getText().toString().trim();
    }

    @Override
    public String picture() {
        return attachFile;
    }

    @Override
    public String content() {
        return contentEt.getText().toString().trim();
    }

    @Override
    public String projectId() {
        return projectId;
    }

    @Override
    public String complaintId() {
        return null;
    }

    @Override
    public String tenantId() {
        return String.valueOf(tenandId);
    }

    @Override
    public Integer status() {
        return null;
    }

    @Override
    public void showToast(String content) {
        hideLoding();
        BToast.showText(this, content);
    }

    @Override
    public void closeDispose(Disposable disposable) {

    }

    String attachFile;

    @Override
    public void getData(UpImageBean upImageBean) {
        attachFile = upImageBean.getResult();
        Log.i("testImage", isImage + "");
        if (attachFile != null) {
            if (isImage == 1) {
                complaintPresenter.submitComplaint();
            } else {
                BToast.showText(this, "请上传图片");
            }
        }
    }

    @Override
    public void showProgress() {
        showLoding();
    }

    @Override
    public void hideProgress() {
        hideLoding();
    }

    @Override
    public void getMsg(SubmitComplaintBean submitComplaintBean) {
        if (submitComplaintBean.getResult() != null) {
            BToast.showText(this, submitComplaintBean.getResult());
            if (complaintView != null) {
                complaintView.setVisibility(View.VISIBLE);
                adviceView.setVisibility(View.INVISIBLE);
                complaintTv.setTextColor(getResources().getColor(R.color.yellow_ff));
                adviceTv.setTextColor(getResources().getColor(R.color.gray_a5));
                type = "1";
                contentEt.getText().clear();
                contentEt.setHint("请详细描述投诉内容");
                imageList.clear();
                imageList.add("0");
                repairImageAdapter.setNewData(imageList);
                isImage = 0;
                submitTv.setText("我要投诉");
                communityTv.setText("请选择小区");
                projectId = null;
            }
            startIntentActivity(ComplaintFeedbackActivity.class, null);
        }
    }

    @Override
    public void getMsg(ComplaintRecordBean complaintRecordBean) {

    }

    @Override
    public void getMsg(ComplaintDetailBean complaintDetailBean) {

    }

    @Override
    public void getMsg(ComplaintEvaluateBean complaintEvaluateBean) {

    }

    @Override
    public void removeImage(int position) {
        imageList.remove(position);
        for (int i = 0; i < imageList.size(); i++) {
            if (imageList.get(i).equals("0")) {
                imageList.remove(i);
            }
        }
        if (imageList.size() < 4) {
            imageList.add("0");
        }
        if (imageList.size() == 1) {
            if (imageList.get(0).equals("0")) {
                isImage = 0;
            }
        }
        repairImageAdapter.setNewData(imageList);

    }
}
